package com.mmall.security;

import com.mmall.model.SysAcl;
import com.mmall.model.SysRole;
import com.mmall.model.SysUser;
import com.mmall.service.SysAclService;
import com.mmall.service.SysRoleAclService;
import com.mmall.service.SysRoleService;
import com.mmall.service.SysUserService;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
@Component
public class MyDetailsService {
    @Resource
    private SysUserService userService;
    @Resource
    private SysRoleAclService sysRoleAclService;
    @Resource
    private SysAclService sysAclService;
    @Resource
    private SysRoleService roleService;

    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
        Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
        SysUser user = null;

        if (user == null) {
            user = userService.findByKeyword(userName);
            if (user == null)
                throw new UsernameNotFoundException(
                        "UserDetailsService.userNotFount");
            //得到用户的权限
            /**
             * 赋予角色
             */
            List<SysRole> sysRoles = roleService.getRoleListByUserId(user.getId());
            /**
             * 赋予权限
             */
            List<Integer> aclIds = sysRoleAclService.getAclIdListByRoleIdList(sysRoles.stream().map(SysRole::getId).collect(Collectors.toList()));
            Set<Integer> set=new HashSet<Integer>();
            set.addAll(aclIds);//给set填充
            List<Integer> list = new ArrayList<Integer>();
            list.addAll(set);
            List<SysAcl> sysAcls = sysAclService.getByIdList(list);
            for (SysAcl authority : sysAcls) {
                System.out.println(authority.getCode()+"+++++++++++++");
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority.getCode());
                auths.add(grantedAuthority);
            }
            user.setAuthorities(auths);
        }

        return user;
    }
}
